﻿using System.Linq;

namespace System.Management.HyperV
{
    /// <summary>
    /// Controls the definition, modification, and destruction of global networking resources such as virtual switches, switch ports, and internal Ethernet ports.
    /// </summary>
    /// <remarks>http://msdn.microsoft.com/en-us/library/cc136938(VS.85).aspx</remarks>
    public class VirtualSwitchManagementService : ManagementServiceBase
    {
        public const string WmiClassName = "Msvm_VirtualSwitchManagementService";

        #region Constructor
        public VirtualSwitchManagementService()
            : base(VirtualSwitchManagementService.WmiClassName)
        {
            throw new NotImplementedException();
        }
        #endregion

        /// <summary>
        /// Creates a new virtual switch.
        /// </summary>
        /// <remarks>http://msdn.microsoft.com/en-us/library/cc136783(VS.85).aspx</remarks>
        /// <param name="switchName">The name of the switch. This name must be unique to all virtual switches in the system.</param>
        /// <param name="switchDisplayName">A user-readable name for the switch.</param>
        /// <param name="maxLearnableAddresses">The maximum number of MAC addresses that can be learned by the switch.</param>
        /// <param name="scopeOfResidence">The initial scope of the switch.</param>
        public Model.VirtualSwitch CreateSwitch(string switchName, string switchDisplayName, uint maxLearnableAddresses, string scopeOfResidence)
        {
            string methodName = "CreateSwitch";

            using (var inParams = this.ManagementServiceInstance.GetMethodParameters(methodName))
            {
                inParams["FriendlyName"] = switchDisplayName;
                inParams["Name"] = switchName;
                inParams["NumLearnableAddresses"] = maxLearnableAddresses;
                inParams["ScopeofResidence"] = null;

                var result = InvokeMethod(methodName, inParams, waitForCompleted: true);

                return new Model.VirtualSwitch((ManagementObject)result.OutParameters["CreatedVirtualSwitch"].Value);
            }
        }

        public Model.VirtualSwitch[] GetVirtualSwitchList()
        {
            var query = new ObjectQuery("SELECT * FROM Msvm_VirtualSwitch");

            using (var searcher = new ManagementObjectSearcher(this.ManagementServiceInstance.Scope, query))
            {
                var switches = from mo in searcher.Get().OfType<ManagementObject>()
                               select new Model.VirtualSwitch(mo);

                return switches.ToArray();
            }
        }
    }
}
